package com.mutual.help.controller;

import com.mutual.help.common.PageResult;
import com.mutual.help.entity.Type;
import com.mutual.help.entity.Users;
import com.mutual.help.service.TypeService;
import com.mutual.help.utils.WeChatResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class TypeController {

    @Autowired
    private TypeService typeService;

    //页面跳转
    @RequestMapping("/type/toPage")
    public String toPage(){
        return "category/list";
    }

    //页面跳转
    @RequestMapping("/type/toAddPage")
    public String toAddPage(){
        return "category/add";
    }

    //页面跳转
    @RequestMapping("/type/toEditPage")
    public String toEditPage(HttpServletRequest request, Model model){
        String id = request.getParameter("id");
        Type type = typeService.getById(Integer.parseInt(id));
        model.addAttribute("type",type);
        return "category/edit";
    }

    @RequestMapping("wx/getAllType")
    @ResponseBody
    public Object getAllType(){
        List<Type> list = typeService.list();
        return WeChatResponseUtil.ok("list", list);
    }

    //分页查询所有分类信息
    @RequestMapping("/type/query")
    @ResponseBody
    public PageResult<Type> list(Integer page, Integer limit) {
        if (page == null) {
            page = 0;
        }
        if (limit == null) {
            limit = 10;
        }
        List<Type> allArticle = typeService.getAllType(page, limit);
        Integer count = typeService.countData();
        return new PageResult<>(allArticle, count);
    }

    @RequestMapping("/type/add")
    @ResponseBody
    public PageResult add(Type type){
        if(typeService.save(type)){
            return new PageResult("新增成功",200);
        }
        return new PageResult("新增失败",400);
    }

    @RequestMapping("/type/delete/{id}")
    @ResponseBody
    public PageResult delete(@PathVariable("id") Integer id){
        if(typeService.removeById(id)){
            return new PageResult("删除成功",200);
        }
        return new PageResult("删除失败",400);
    }

    @RequestMapping("/type/edit")
    @ResponseBody
    public PageResult update(Type type){
        if(typeService.updateById(type)){
            return new PageResult("修改成功",200);
        }
        return new PageResult("修改失败",400);
    }
}
